<?php


namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\ArraySort;
use StarCloud\Library\HttpCurl;

class ZhuJie
{
    use HttpCurl;
    /* @var $httpClient HttpClient */
    private $httpClient = null;

    private $token = "";
    private $username = "抖啦咪";
    private $password = "doulami1234edc";
    private $domain = "https://yueshun.third.fengzhir.top";

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getQrCode($path, $type)
    {
        $body = [
            'path' => $path,
            'type' => $type,
        ];
        $header = $this->getHeader();
        $header['Content-Type'] = 'application/x-www-form-urlencoded';
        $response =  $this->httpClient->sendPostRequestUrlEncode("https://androidapi4.yc.ifeng.com/api/CZMGZ/getQRCode?", $body, $header);
        $json = json_decode($response->getBody()->getContents(), true);

        return $json['data']['img'] ?? "";
    }

    public function createKeyWord()
    {
        $url = $this->domain . "/api/v1/createKeyWords";
        $response =  $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json['data'] ?? false;
    }

    public function passphrase($senceId, $bookId, $appId, $name, $keyWord)
    {
        $body = [
            'name' => $name,
            'app_id' => $appId,
            'keywords' => $keyWord,
            'custom_params' => $senceId,
            'content_id' => $bookId,
        ];

        $response =  $this->httpClient->sendPostRequest($this->domain . "/api/v1/createRecommend?", $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json['data'];
    }

    public function getCategory()
    {
        $cacheResult = $this->getCacheCategory();

        if (!empty($cacheResult)) {
            return  $cacheResult;
        }

        $body = [];
        $response =  $this->httpClient->sendGetRequest($this->domain . "/api/v1/tags?", $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        $res[] =[
            'id' => 0,
            'name' => "全部",
        ];

        foreach ($json['data'] as $item) {
            $res[] = [
                'id' => $item['id'],
                'name' => $item['tag_name']
            ];
        }

        $this->setCacheCategory($res);
        return $res;
    }

    public function setCacheCategory($res) {

        if (is_array($res)) {
            $res = json_encode($res);
        }

        $this->cacheClass->set("zhujie:novel:category", $res, 86400 * 10);
    }

    public function getCacheCategory() {
        $result = $this->cacheClass->get("zhujie:novel:category");
        $result = json_decode($result, true);

        return empty($result) ? [] : $result;
    }

    public function getApps()
    {
        $url = $this->domain . "/api/v1/getApp";

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data'];
        }
        return [];
    }

    public function setCacheToken($token, $expire)
    {
        $keyName = "zhujie_token";
        $this->cacheClass->set($keyName, $token, $expire);
    }
    public function getCacheToken()
    {
        $keyName = "zhujie_token";
        return $this->cacheClass->get($keyName);
    }

    private function getHeader()
    {
        $token = $this->getCacheToken();
        if ($token) {
            $this->token = $token;
        }else {
            $url = $this->domain . "/api/v1/login";
            $body = [
                'username' => $this->username,
                'password' => $this->password,
            ];
            $header['Content-Type'] = 'application/json';
            $response = $this->httpClient->sendPostRequest($url, $body, $header);

            $json = json_decode($response->getBody()->getContents(), true);

            if (isset($json['code']) && $json['code'] == 0) {
                $this->token = $json['data']['access_token'];
                $this->setCacheToken($json['data']['access_token'], $json['data']['expires_in'] - 100);
            }
        }
        return [
            'Authorization' => 'Bearer ' . $this->token,
            'Content-Type' => 'application/json',
        ];
    }

    public function queryOrder($page, $startTime, $endTime)
    {
        $body = [
            'pageNum' => $page,
            'pageSize' => 10,
            'startTime' => $startTime,
            'endTime' => $endTime,
        ];

        $response =  $this->httpClient->sendGetRequest($this->domain . "/api/v1/payList?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        var_dump($json);
        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data'];
        }

        return [];
    }

    public function getList($page, $categoryId = 0, $name = "", $size = 10)
    {
        $body = [
            'pageNum' => $page,
            'pageSize' => $size,
        ];
        if (!empty($name)) {
            $body['contentName'] = $name;
        }
        if (!empty($categoryId)) {
            $body['tagId'] = $categoryId;
        }
        $key = 'fh_novel_'.md5(json_encode($body));

        $data = $this->cacheClass->get($key);
        if ($data) {
            return json_decode($data, true);
        }
        $response =  $this->httpClient->sendGetRequest($this->domain . "/api/v1/storyList?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            $res = [];
            foreach ($json['data'] as &$item) {
                $item['cover_url'] =  $item['cover'] ?? "";
                $item['id'] =  $item['id'] ?? "";
                $item['describe'] =  $item['description'] ?? "";
                $item['name'] =  $item['title'] ?? "";
                $item['publish_url'] =  $item['publish_url'] ?? "";
                if ($item['is_show_city'] == 1) {
                    $res[] = $item;
                }
            }
            $this->cacheClass->set($key, json_encode([
                'data' => $res
            ]), 1800);

            return [
                'data' => $res
            ];
        }
        return [
            'data' => [],
        ];
    }

    public function getBookInfo($bookId)
    {
        $bookInfo = $this->getCacheBookInfo($bookId);

        if (!empty($bookInfo)) {
            return  $bookInfo;
        }
        $body = [
            'contentId' => intval($bookId)
        ];
        $response =  $this->httpClient->sendGetRequest($this->domain . "/api/v1/content?".http_build_query($body), [], $this->getHeader());
        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            $json['data']['chapter'] = $this->getChapter($bookId);
            $json['data']['chapterContent'] = '';
            foreach ($json['data']['chapter'] as $chapter) {
                $json['data']['chapterContent'] .= $chapter['content'] . "\n";
            }

            return $this->setCacheBookInfo($bookId, $json['data']);
           
        }

        return [];
    }

    public function getChapter($bookId)
    {
        $body = [
            'contentId' => intval($bookId),
            'free' => 1,
        ];
        $response = $this->httpClient->sendGetRequest($this->domain . "/api/v1/chapter?" . http_build_query($body), [], $this->getHeader());
        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data'];
        }

        return [];
    }

    public function getBookCacheKey($bookId)
    {
        return "20231026:zhujie:novel:bookinfo:".$bookId;
    }

    private function setCacheBookInfo($bookId, $bookInfo)
    {
        $bookInfo['authorName'] = $bookInfo['authorName'] ?? "";
        $bookInfo['bookDesc'] = $bookInfo['description'] ?? "";
        $bookInfo['bookId'] = $bookInfo['id'] ?? "";
        $bookInfo['bookName'] = $bookInfo['title'] ?? "";
        $bookInfo['bookPhoto'] = $bookInfo['cover'] ?? "";
        $bookInfo['categoryName'] = $bookInfo['tags'] ?? "";
        if (is_array($bookInfo)) {
            $bookInfo = json_encode($bookInfo);
        }

        $this->cacheClass->set($this->getBookCacheKey($bookId), $bookInfo, 86400);

        return json_decode($bookInfo, true);
    }

    public function getCacheBookInfo($bookId)
    {
        $bookInfo = $this->cacheClass->get($this->getBookCacheKey($bookId));
        $bookInfo = json_decode($bookInfo, true);

        return empty($bookInfo) ? false : $bookInfo;
    }
}